#include "TopK.h"

void CreateNum(size_t size) {
	srand(time(NULL));
	FILE* randnum = fopen("randnum.txt", "w");
	if (randnum == NULL) {
		perror("fopen fail");
		exit(3);
	}
	for (size_t i = 0; i < size; i++) {
		int num = rand() % size + 1;
		int suc = fprintf(randnum, "%d\n", num);
		if (!suc > 0) {
			perror("fprintf fail");
			exit(4);
		}
	}
	fclose(randnum);
	randnum = NULL;
}

int* GetTopK(FILE* randnum, const size_t size, const size_t K) {
	int* arr = (int*)malloc(sizeof(int) * K);
	if (arr == NULL) {
		perror("malloc fail!");
		exit(5);
	}
	int i = 0;
	for (i = 0; i < K; i++) {
		errno = 0;
		int success = fscanf(randnum, "%d", &arr[i]);
		if (success != 1) {
			if (errno != 0) {
				perror("fscanf");
			}
			else {
				printf("Error: No matching Characters!\n");
			}
			exit(6);
		}
		HeapAdjustDown(arr, i + 1, 0, 'S');
	}
	while (i < size) {
		int num = 0;
		errno = 0;
		int success = fscanf(randnum, "%d", &num);
		if (success != 1) {
			if (errno != 0) {
				perror("fscanf");
			}
			else {
				printf("Error: No matching Characters!\n");
			}
			exit(6);
		}
		if (arr[0] < num) {
			arr[0] = num;
			HeapAdjustDown(arr, K, 0, 'S');
		}
		i++;
	}
	HeapAdjustDown(arr, K, 0, 'B');
	return arr;
}

void PrintTopK(int* arr, int K) {
	while (K > 0) {
		printf("%d ", arr[0]);
		Swap(&arr[0], &arr[K - 1]);
		K--;
		HeapAdjustDown(arr, K, 0, 'B');
	}
}